import React, { useEffect, useState } from "react";
import { HashRouter, Routes, Route, Navigate } from "react-router-dom";
import routes from "./router.config";
import ComponentWrap from "./ComponentWrap";
import { useSelector, useDispatch } from "react-redux";
import { getToken } from "@/config/cookie.js";
import ajax from "@/services";
import { message } from "antd";
import { setUser } from "@/store/user.js";

function RouterMap() {
  const dispatch = useDispatch();
  const storeRoutes = useSelector((state) => state.user.route);

  const renderElement = (route) => {
    return (
      <>
        {route?.needPermission && !storeRoutes.includes(route.name) ? (
          <Navigate to="/403" />
        ) : (
          <ComponentWrap
            data={{
              path: route?.path,
              breadcrumb: route?.breadcrumb || [],
            }}
          >
            <route.component />
          </ComponentWrap>
        )}
      </>
    );
  };

  useEffect(() => {
    judgeLogin();
  }, []);

  // 判断登录状态
  const judgeLogin = () => {
    const tokenStr = getToken();
    if (tokenStr) {
      getInfoData();
    } else {
      toLogin();
    }
  };

  // 获取用户信息
  function getInfoData(obj) {
    ajax.getUserInfo(obj).then(
      (res) => {
        dispatch(setUser(res.data));
      },
      (err) => {
        toLogin();
        !err.message && message.error("服务器异常");
      }
    );
  }

  // 返回登录页
  function toLogin() {
    const origin = window.location.origin;
    const pathname = window.location.pathname;
    window.location.href = `${origin}${pathname}#/login`;
  }

  return (
    <HashRouter>
      <Routes>
        {routes.map((route) => {
          if (route.children && route.children.length) {
            return (
              <Route
                element={<route.component />}
                path={route.path}
                key={route.path}
              >
                <Route path="/" index element={<Navigate to={"/home"} />} />
                {route.children.map((route2) => {
                  return (
                    <Route
                      path={route2.path}
                      key={route2.path}
                      element={renderElement(route2)}
                    />
                  );
                })}
              </Route>
            );
          } else {
            return (
              <Route
                path={route.path}
                key={route.path}
                element={renderElement(route)}
              />
            );
          }
        })}
        <Route path="*" element={<Navigate to="/home" />} />
      </Routes>
    </HashRouter>
  );
}

export default RouterMap;
